#include "tcpserverwidget.h"
#include "ui_tcpserverwidget.h"
QTcpSocket* TcpServerWidget::qTcpSocket = NULL;
#define BindPort 8000
TcpServerWidget::TcpServerWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TcpServerWidget)
{
    ui->setupUi(this);
    ui->textEditShow->setReadOnly(true);


    ui->textEditShow->setStyleSheet(QString("QTextEdit{"
                                            "font-weight:bold;"
                                            "color:green;"
                                            "}"));


    QTcpServer* qTcpServer = new QTcpServer(this);

    qTcpServer->listen(QHostAddress::Any,BindPort);
    this->setWindowTitle(QString("服务端口:%1").arg(BindPort));
    connect(qTcpServer,&QTcpServer::newConnection,
            [=](){
        qTcpSocket =  qTcpServer->nextPendingConnection();
        QString peerAddress =  qTcpSocket->peerAddress().toString();
        quint16 peerPort =  qTcpSocket->peerPort();
        QString peerName =  qTcpSocket->peerName();
        cout<<"peerIP:"<<peerAddress;
        cout<<"peerPort:"<<peerPort;

        QString text = QString("客户端已连接(网络IP=%1 , 端口:%2 )")
                .arg(peerAddress).arg(peerPort);
        ui->textEditShow->append(text);

        connect(qTcpSocket,&QTcpSocket::readyRead,
                [=](){
            QByteArray qByteArray = qTcpSocket->readAll();
            ui->textEditShow->append(QString("客户端：").append(qByteArray));
        });
    });
}

TcpServerWidget::~TcpServerWidget()
{
    delete ui;
}

void TcpServerWidget::on_closeButton_clicked()
{
    if (qTcpSocket && qTcpSocket->isOpen()){
        QString peerAddress =  qTcpSocket->peerAddress().toString();
        quint16 peerPort =  qTcpSocket->peerPort();
        cout << peerPort;
        QString text =  peerAddress.append(":%1").arg(peerPort);
        cout << text;
        qTcpSocket->disconnectFromHost();
        qTcpSocket->close();
        if (!qTcpSocket->isOpen()) {
            ui->textEditShow->append(QString("已断开%1链接").arg(text));
        }
        qTcpSocket = NULL;
    }else {
        ui->textEditShow->append(QString("套接字处于未连接状态"));
    }
}

void TcpServerWidget::on_sendButton_clicked()
{
    QString sendText = ui->textEditSend->toPlainText();
    cout<<sendText.isEmpty();
    if (qTcpSocket && qTcpSocket->isOpen()) {
        if ( !sendText.isEmpty()) {
            int writeResult = qTcpSocket->write(sendText.toUtf8().data());
            if (writeResult==-1) {
                ui->textEditShow->append(QString("发生错误,无网络连接,或者客户端已断开连接！"));
                return;
            }
            ui->textEditSend->clear();
        }
    }else {
        ui->textEditShow->append(QString("未有可用的套接字处理！"));
    }
}
